import time

from alphalib.product.api.trade import get_twap_symbol_info_list, place_order
from alphalib.product.api.market import load_market, fetch_binance_ticker_data
from alphalib.product.api.position import get_spot_position, bn_transfer_u_to_spot, bn_transfer_spot_to_u
from alphalib.product.utils.functions import calc_spot_need_usdt_amount


def proceed_swap_order(exchange, symbol_order, account_info):
    """
    处理合约下单
    :param exchange:        交易所对象
    :param symbol_order:    下单数据
    :param account_info:    用户配置
    """
    # =====获取合约与现货的信息。最小下单量，下单精度等
    # =获取U本位合约交易对的信息
    swap_symbol_list, swap_min_qty, swap_price_precision, swap_min_notional = load_market(exchange, symbol_type='swap')

    max_one_order_amount = account_info['max_one_order_amount']  # 最大拆单金额
    twap_interval = account_info['twap_interval']  # 下单间隔时间
    wechat_webhook_url = account_info['wechat_webhook_url']  # 当前账号的机器人

    # ===使用twap算法拆分订单
    swap_order = symbol_order[symbol_order['symbol_type'] == 'swap']
    twap_swap_symbol_info_list = get_twap_symbol_info_list(swap_order, max_one_order_amount)

    # ===遍历下单
    for i in range(len(twap_swap_symbol_info_list)):
        # 获取合约币种的最新价格
        symbol_last_price = fetch_binance_ticker_data(exchange)
        # 逐批下单
        place_order(exchange, twap_swap_symbol_info_list[i], symbol_last_price, swap_min_qty,
                    swap_price_precision, swap_min_notional, symbol_type='swap', wechat_webhook_url=wechat_webhook_url)
        # 下单间隔
        print(f'等待 {twap_interval}s 后继续下单')
        time.sleep(twap_interval)
    # 清理数据
    del swap_symbol_list, swap_min_qty, swap_price_precision, swap_min_notional


def proceed_spot_order(exchange, symbol_order, account_info, select_coin, is_only_sell=False):
    """
    处理现货下单
    :param exchange:        交易所对象
    :param symbol_order:    下单数据
    :param account_info:    用户配置
    :param select_coin:     选币数据
    :param is_only_sell:    是否仅仅进行卖单交易
    """
    # =====获取合约与现货的信息。最小下单量，下单精度等
    # =加载现货交易对信息
    spot_symbol_list, spot_min_qty, spot_price_precision, spot_min_notional = load_market(exchange, symbol_type='spot')

    max_one_order_amount = account_info['max_one_order_amount']  # 最大拆单金额
    twap_interval = account_info['twap_interval']  # 下单间隔时间
    wechat_webhook_url = account_info['wechat_webhook_url']  # 当前账号的机器人

    # ===现货处理
    spot_order = symbol_order[symbol_order['symbol_type'] == 'spot']
    # 判断是否需要现货下单
    if not spot_order.empty:  # 如果使用了现货数据实盘，则进行现货下单
        # =使用twap算法拆分订单
        short_order = spot_order[spot_order['实际下单资金'] <= 0]
        long_order = spot_order[spot_order['实际下单资金'] > 0]
        # 判断是否只卖现货
        if is_only_sell:  # 如果是仅仅交易卖单，只进行拆单
            twap_spot_short_list = get_twap_symbol_info_list(short_order, max_one_order_amount)
            twap_spot_symbol_info_list = twap_spot_short_list
        else:  # 如果是仅仅交易买单，拆单，划转资金去现货账户
            twap_spot_long_list = get_twap_symbol_info_list(long_order, max_one_order_amount)
            twap_spot_symbol_info_list = twap_spot_long_list

            # =划转资金到现货账户
            time.sleep(5)
            transfer_amount = calc_spot_need_usdt_amount(account_info, select_coin, spot_order)
            print('transfer_amount', transfer_amount)
            if transfer_amount > 0:
                # 转资金到现货账户
                bn_transfer_u_to_spot(exchange, round(transfer_amount - 1, 1))

        # =现货遍历下单
        for i in range(len(twap_spot_symbol_info_list)):
            # 获取现货币种的最新价格
            symbol_last_price = fetch_binance_ticker_data(exchange, symbol_type='spot')
            # 逐批下单
            place_order(exchange, twap_spot_symbol_info_list[i], symbol_last_price, spot_min_qty,
                        spot_price_precision, spot_min_notional, symbol_type='spot',
                        wechat_webhook_url=wechat_webhook_url)
            # 下单间隔
            print(f'等待 {twap_interval}s 后继续下单')
            time.sleep(twap_interval)

        # =将现货中的U转入的合约账号
        spot_position = get_spot_position(exchange)
        if 'USDT' in spot_position['symbol'].to_list():
            usdt = spot_position.loc[spot_position['symbol'] == 'USDT', '当前持仓量'].iloc[0]
            # 转资金到合约账户
            bn_transfer_spot_to_u(exchange, round(usdt - 1, 1))
    # 清理数据
    del spot_symbol_list, spot_min_qty, spot_price_precision, spot_min_notional

